#include "battle.h"
#include <QObject>
#include "ui_battle.h"

#include"GlobalObject.h"

#include <QMediaPlayer>  // 添加这行
#include <QAudioOutput>


battle::battle(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::battle)
    , m_playerPokemon(nullptr)
    , m_enemyPokemon(nullptr)
    , m_skillPlayer(new QMediaPlayer(this))
    , m_isPlayerTurn(true)
{
    ui->setupUi(this);

    QAudioOutput* audioOutput = new QAudioOutput(this);
    m_skillPlayer->setAudioOutput(audioOutput);

    this->setAutoFillBackground(true);           // 启用自动填充背景
    this->setAttribute(Qt::WA_StyledBackground); // 确保样式表应用到背景

    ui->battleLog->setReadOnly(true);
    ui->skillButton1->setEnabled(false);
    ui->skillButton2->setEnabled(false);
    ui->skillButton3->setEnabled(false);
    ui->skillButton4->setEnabled(false);

    //切换按钮的隐藏初始化
    ui->member1Button_1->setVisible(false);
    ui->member1Button_2->setVisible(false);
    ui->member1Button_3->setVisible(false);
    ui->member1Button_4->setVisible(false);
    ui->member1Button_5->setVisible(false);
    ui->member1Button_6->setVisible(false);


    for(int i = 1; i <= 6; i++) {
        QPushButton* button = findChild<QPushButton*>(QString("member1Button_%1").arg(i));
        if(button && (i-1) < m_playerTeam.size()) {
            button->setText(m_playerTeam[i-1]->getName());
        }
    }

    //battle里的connect连接
    connect(ui->runButton, &QPushButton::clicked, [=]() {
        //因为此类里面没有widget的对象，所以想要返回只能用父类的函数调控父类
        emit back();
    });
    //switchbutton的连接
    connect(ui->switchButton, &QPushButton::clicked, this, &battle::switchpokemon);
    //各个切换按钮的连接
    connect(ui->member1Button_1, &QPushButton::clicked, this, [this]() {
        ui->battleLog->append(QString("Player 选择了 %1 上场").arg(m_playerTeam[0]->getName()));
        setPlayerPokemon(m_playerTeam[0]); // 使用索引0表示第1个成员
        m_isPlayerTurn = 0;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
        hideswitch();
    });
    connect(ui->member1Button_2, &QPushButton::clicked, this, [this]() {
        ui->battleLog->append(QString("Player 选择了 %1 上场").arg(m_playerTeam[1]->getName()));
        setPlayerPokemon(m_playerTeam[1]); // 使用索引1表示第2个成员
        m_isPlayerTurn = 0;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
        hideswitch();
    });
    connect(ui->member1Button_3, &QPushButton::clicked, this, [this]() {
        ui->battleLog->append(QString("Player 选择了 %1 上场").arg(m_playerTeam[2]->getName()));

        setPlayerPokemon(m_playerTeam[2]); // 使用索引2表示第3个成员
        m_isPlayerTurn = 0;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
        hideswitch();
    });
    connect(ui->member1Button_4, &QPushButton::clicked, this, [this]() {
        ui->battleLog->append(QString("Player 选择了 %1 上场").arg(m_playerTeam[3]->getName()));
        setPlayerPokemon(m_playerTeam[3]); // 使用索引3表示第4个成员
        m_isPlayerTurn = 0;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
        hideswitch();
    });
    connect(ui->member1Button_5, &QPushButton::clicked, this, [this]() {
        ui->battleLog->append(QString("Player 选择了 %1 上场").arg(m_playerTeam[4]->getName()));
        setPlayerPokemon(m_playerTeam[4]); // 使用索引4表示第5个成员
        m_isPlayerTurn = 0;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
        hideswitch();
    });
    connect(ui->member1Button_6, &QPushButton::clicked, this, [this]() {
        ui->battleLog->append(QString("Player 选择了 %1 上场").arg(m_playerTeam[5]->getName()));
        setPlayerPokemon(m_playerTeam[5]); // 使用索引5表示第6个成员
        m_isPlayerTurn = 0;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
        hideswitch();
    });

    connect(ui->endButton,&QPushButton::clicked,this,[this](){
        emit back();
    });
}

battle::~battle()
{
    delete m_skillPlayer;
    delete ui;
}


void battle::on_runButton_clicked() {ui->battleLog->clear();}




void battle::setPlayerPokemon(Pokemon* pokemon) {

    if (m_playerPokemon) {
        m_playerPokemon->disconnect(this);
    }
    m_playerPokemon = pokemon;
    ui->playerImage->setPixmap(pokemon->getImage().scaled(200, 200, Qt::KeepAspectRatio));
    ui->playerName->setStyleSheet("color: #66ccff; font-size: 28px; font-weight: bold;");
    ui->playerName->setText(pokemon->getName());
    ui->playerHP->setText(QString("HP: %1/%2").arg(pokemon->getHP()).arg(pokemon->getMaxHP()));

    connect(pokemon, &Pokemon::hpChanged, [this](int hp, int maxHP) {
        ui->playerHP->setText(QString("HP: %1/%2").arg(hp).arg(maxHP));
    });
    connect(pokemon, &Pokemon::skillused, this, [this](int index, Pokemon *user) {
        QTimer::singleShot(500, this, [this, index, user]() {
            // 在嵌套Lambda中使用捕获的参数
            onSkillUsed(index, user);
        });
    });
    connect(pokemon, &Pokemon::fainted, this, &battle::onFainted);

    const auto &skills = pokemon->getSkills();
    if (skills.size() > 0)
        ui->skillButton1->setText(skills[0]->getName());
    if (skills.size() > 1)
        ui->skillButton2->setText(skills[1]->getName());
    if (skills.size() > 2)
        ui->skillButton3->setText(skills[2]->getName());
    if (skills.size() > 3)
        ui->skillButton4->setText(skills[3]->getName());

    // 启用技能按钮
    for (int i = 0; i < qMin(4, skills.size()); ++i) {
        QPushButton *btn = this->findChild<QPushButton *>(QString("skillButton%1").arg(i + 1));
        if (btn)
            btn->setEnabled(true);
    }
}

void battle::setEnemyPokemon(Pokemon *pokemon)
{
    if (m_enemyPokemon) {
        m_enemyPokemon->disconnect(this);
    }
    m_enemyPokemon = pokemon;

    ui->enemyImage->setPixmap(pokemon->getImage().scaled(200, 200, Qt::KeepAspectRatio));
    ui->enemyName->setStyleSheet("color: #66ccff; font-size: 28px; font-weight: bold;");
    ui->enemyName->setText(pokemon->getName());
    ui->enemyHP->setText(QString("HP: %1/%2").arg(pokemon->getHP()).arg(pokemon->getMaxHP()));

    connect(pokemon, &Pokemon::hpChanged, [this](int hp, int maxHP) {
        ui->enemyHP->setText(QString("HP: %1/%2").arg(hp).arg(maxHP));
    });

    connect(pokemon, &Pokemon::skillused, this, [this](int index, Pokemon *user) {
        QTimer::singleShot(500, this, [this, index, user]() {
            // 在嵌套Lambda中使用捕获的参数
            onSkillUsed(index, user);
        });
    });
    connect(pokemon, &Pokemon::fainted, this, &battle::onFaintedenemy);
}

void battle::startBattle()
{
    ui->battleLog->append("战斗开始！");
    ui->endButton->setVisible(false);
    m_isPlayerTurn = true;
    updateUI();
}

void battle::on_skillButton1_clicked()
{
    if (m_isPlayerTurn && m_playerPokemon) {
        playSkillSound(m_playerPokemon->getSkills()[0]);
        m_playerPokemon->useSkill(0, m_enemyPokemon);
        m_isPlayerTurn = false;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
    }
}

void battle::on_skillButton2_clicked()
{
    if (m_isPlayerTurn && m_playerPokemon) {
        playSkillSound(m_playerPokemon->getSkills()[1]);
        m_playerPokemon->useSkill(1, m_enemyPokemon);
        m_isPlayerTurn = false;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
    }
}

void battle::on_skillButton3_clicked()
{
    if (m_isPlayerTurn && m_playerPokemon) {
        playSkillSound(m_playerPokemon->getSkills()[2]);
        m_playerPokemon->useSkill(2, m_enemyPokemon);
        m_isPlayerTurn = false;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
    }
}

void battle::on_skillButton4_clicked()
{
    if (m_isPlayerTurn && m_playerPokemon) {
        playSkillSound(m_playerPokemon->getSkills()[3]);
        m_playerPokemon->useSkill(3, m_enemyPokemon);
        m_isPlayerTurn = false;
        QTimer::singleShot(1000, this, &battle::enemyTurn);
    }
}


void battle::enemyTurn()
{
    if (!m_isPlayerTurn && m_enemyPokemon->isAlive()) {
        ui->battleLog->append(QString("%1的回合！").arg(m_enemyPokemon->getName()));
        int index = rand() % m_enemyPokemon->getSkills().size();
        playSkillSound(m_enemyPokemon->getSkills()[index]);
        m_enemyPokemon->useSkill(index, m_playerPokemon);
        m_isPlayerTurn = true;
        QTimer::singleShot(1000, this, &battle::updateUI);
    }
}

void battle::onSkillUsed(int index, Pokemon *user)
{
    // 1. 安全检查
    if (!user || index < 0 || index >= user->getSkills().size()) {
        qWarning() << "Invalid skill index or null Pokemon!";
        return;
    }

    // 2. 获取技能和使用者名称
    Skill *skill = user->getSkills()[index];
    QString userName = (user == m_playerPokemon) ? m_playerPokemon->getName()
                                                 : m_enemyPokemon->getName();

    // 3. 更新战斗日志
    switch (skill->getSkillType())
    {
    case SkillType::Damage:
        if (ui && ui->battleLog) {
            ui->battleLog->append(
                QString("%1 使用了 %2 对 %4 造成了 %3 的伤害")
                    .arg(userName)
                    .arg(skill->getName())
                    .arg(damage)
                    .arg(defendername(user))
                );
        }
        break;
    case SkillType::Heal:
        if (ui && ui->battleLog) {
            ui->battleLog->append(
                QString("%1 使用了 %2 回复自身 %3 血")
                    .arg(userName)
                    .arg(skill->getName())
                    .arg(damage)
                );
        }
        break;
    defalut:
        break;
    }
}

void battle::onFainted()
{
    Pokemon *fainted = qobject_cast<Pokemon *>(sender());
    ui->battleLog->append(QString("%1失去战斗能力！").arg(fainted->getName()));
    for(int i = 0; i < m_playerTeam.size() && i < playermax; i++) {
        if(m_playerTeam[i]->isAlive()) {
            setPlayerPokemon(m_playerTeam[i]);
            QTimer::singleShot(1000, this, &battle::stop1);
            ui->battleLog->append(QString("我方切换了 %1 上场")
                                      .arg(m_playerTeam[i]->getName()));
            break; // 找到一个存活的宝可梦后就停止
        }
    }
    QTimer::singleShot(1000, this, &battle::checkBattleEnd);
}
void battle::onFaintedenemy()
{
    Pokemon *fainted = qobject_cast<Pokemon *>(sender());
    ui->battleLog->append(QString("%1失去战斗能力！").arg(fainted->getName()));
    for(int i = 0; i < m_enemyTeam.size() && i < playermax; i++) {
        if(m_enemyTeam[i]->isAlive()) {
            setEnemyPokemon(m_enemyTeam[i]);
            QTimer::singleShot(1000, this, &battle::stop1);
            ui->battleLog->append(QString("敌方切换了 %1 上场")
                                      .arg(m_enemyTeam[i]->getName()));
            break; // 找到一个存活的宝可梦后就停止
        }
    }

    QTimer::singleShot(1000, this, &battle::checkBattleEnd);
}

void battle::checkBattleEnd()
{
    if (!allalived(m_playerTeam)) {
        ui->battleLog->append("战斗结束！你输了。");
        // 禁用所有技能按钮
        ui->skillButton1->setEnabled(false);
        ui->skillButton2->setEnabled(false);
        ui->skillButton3->setEnabled(false);
        ui->skillButton4->setEnabled(false);
        ui->endButton->setVisible(true);

    } else if (!allalived(m_enemyTeam)) {
        ui->battleLog->append("战斗结束！你赢了。");
        ui->skillButton1->setEnabled(false);
        ui->skillButton2->setEnabled(false);
        ui->skillButton3->setEnabled(false);
        ui->skillButton4->setEnabled(false);
        ui->endButton->setVisible(true);
    }
}

void battle::updateUI()
{
    ui->playerHP->setText(
        QString("<span style='color: red;'>HP: %1/%2</span>").arg(m_playerPokemon->getHP()).arg(m_playerPokemon->getMaxHP()));
    ui->enemyHP->setText(
        QString("<span style='color: red;'>HP: %1/%2</span>").arg(m_enemyPokemon->getHP()).arg(m_enemyPokemon->getMaxHP()));

    // 显示当前回合
    ui->battleLog->append(m_isPlayerTurn ? "你的回合！"
                                         : QString("%1的回合！").arg(m_enemyPokemon->getName()));
}

void battle::addplayer(Pokemon *pokemon)
{
    m_playerTeam.push_back(pokemon);
    playermax += 1;
}

void battle::addenemy(Pokemon* pokemon)
{
    m_enemyTeam.push_back(pokemon);

}



//切换宝可梦
void battle::switchpokemon(){

    for(int i = 1; i <= 6; i++) {
        QPushButton* button = findChild<QPushButton*>(QString("member1Button_%1").arg(i));
        if(button) {
            bool canSwitch = (i-1 < m_playerTeam.size()) && m_playerTeam[i-1]->isAlive();
            button->setEnabled(canSwitch);
            if (canSwitch) {
                button->setText(m_playerTeam[i-1]->getName());
            }
            button->setVisible(!button->isVisible());

        }
    }
}

QString battle::defendername(Pokemon *user)
{
    if (user->getName() == m_enemyPokemon->getName())
        return m_playerPokemon->getName();
    else
        return m_enemyPokemon->getName();
}

void battle::hideswitch()
{
    ui->member1Button_1->setVisible(false);
    ui->member1Button_2->setVisible(false);
    ui->member1Button_3->setVisible(false);
    ui->member1Button_4->setVisible(false);
    ui->member1Button_5->setVisible(false);
    ui->member1Button_6->setVisible(false);
}

bool battle::allalived(QVector<Pokemon*> m_playerTeam)
{
for(int i = 0; i < m_playerTeam.size(); i++)
    {
        if(m_playerTeam[i]->isAlive())
    {qDebug() << QString("%1  活着").arg(m_playerTeam[i]->getName());
        return 1;}

    }

    return 0;
}

void battle::stop1(){qDebug("暂停·一会");}

void battle::playSkillSound(Skill* skill)
{
    if (skill && !skill->getSoundPath().isEmpty()) {
        m_skillPlayer->stop();
        m_skillPlayer->setSource(QUrl(skill->getSoundPath()));
        m_skillPlayer->play();
    }
}
